package com.fsds.crem.web.timetask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fsds.crem.core.constant.Globals;
import com.fsds.crem.core.util.ApplicationContextUtil;
import com.fsds.crem.core.util.LogUtil;
import com.fsds.crem.core.util.SendMailUtil;
import com.fsds.crem.web.entity.AccountInfo;
import com.fsds.crem.web.entity.EmailMessage;
import com.fsds.crem.web.service.EmailMessageService;
import com.fsds.crem.web.service.ReportEmailService;

public class SendEmailTimeTask {
	
	public void sendEmailRun(){
		
		LogUtil.info("~~~~~~~~~~~~~~~~email~~~~begin~~~~~~~~~~~~~~~~~~~~");
		
		try {
			
			ReportEmailService reportEmailService = 
					(ReportEmailService) ApplicationContextUtil.getBean("reportEmailService");
			
			EmailMessageService emailMessageService = 
					(EmailMessageService) ApplicationContextUtil.getBean("emailMessageService");
			
			// 获取需要发出的邮件信息
			EmailMessage emailMessage_search = new EmailMessage();
			emailMessage_search.setState(Globals.EMAIL_STATE_NOTSENT);
			List<EmailMessage> emailMessageList = emailMessageService.findEmailMessageByState(emailMessage_search);
			
			if (emailMessageList != null && emailMessageList.size() > 0) {

				for (EmailMessage emailMessage : emailMessageList) {
					
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("content", emailMessage.getEmailContent()); // 邮件内容
					map.put("imgpath", "http://www.logoquan.com/upload/list/20151219/logoquan14509819423.PNG");
					
					List<AccountInfo> accountInfoList = reportEmailService.findByInstalled(emailMessage.getReportType());
					
					// 有收件人
					if(accountInfoList != null && accountInfoList.size() > 0){
						
						List<String> addressList = new ArrayList<String>();
						for(AccountInfo accountInfo : accountInfoList){
							addressList.add(accountInfo.getEmail());
						}
						
						// 发送邮件
						boolean flag;
						flag = SendMailUtil.sendFtlMail(addressList, 
								"销售日报表", emailMessage.getTemplateName(), map,
								emailMessage.getAttachmentUrl(),emailMessage.getAttachmenName());

						if(flag) {
							
							EmailMessage emailMessage_update = new EmailMessage();
							emailMessage_update.setId(emailMessage.getId());
							emailMessage_update.setState(Globals.EMAIL_STATE_ALREADYSENT);
							// 修改状态
							emailMessageService.updateEmailMessageStateById(emailMessage_update);
						}
					}
				}
			}
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		LogUtil.info("~~~~~~~~~~~~~~~email~~~~~end~~~~~~~~~~~~~~~~~~~~");
	}
	
	
}
